<template>
  <div>
    <a-upload
      :before-upload="beforeUpload"
      :multiple="false"
      :show-upload-list="false"
      accept=".xls,.xlsx"
    >
      <a-button> <UploadOutlined /> </a-button>
    </a-upload>
    <a-table :data-source="data" :columns="columns">
      <!-- 使用 bodyCell 插槽来自定义单元格内容 -->
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.key === 'resume'">
          {{ truncateText(text, 100) }}
        </template>
        <template v-else-if="column.key === 'signature'">
          {{ truncateText(text, 20) }}
        </template>
        <template v-else>
          {{ text }}
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import * as XLSX from "xlsx";

// 示例数据
const data = ref([]);

// 定义列
const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "Gender",
    dataIndex: "gender",
    key: "gender",
  },
  {
    title: "Resume",
    dataIndex: "resume",
    key: "resume",
  },
  {
    title: "Signature",
    dataIndex: "signature",
    key: "signature",
  },
];

// 文件上传前处理
const beforeUpload = (file) => {
  handleFile(file);
  return false; // 阻止默认上传行为
};

// 处理文件
const handleFile = async (file) => {
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    const binaryStr = e.target.result;
    const workbook = XLSX.read(binaryStr, { type: "binary" });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const parsedData = XLSX.utils.sheet_to_json(sheet, { header: 1 });

    // 将第一行作为表头
    if (parsedData.length > 0) {
      const headers = parsedData.shift();

      // 转换数据格式
      const transformedData = parsedData.map((row) => {
        return {
          name: row[headers.indexOf("Name")],
          gender: row[headers.indexOf("Gender")],
          resume: row[headers.indexOf("Resume")],
          signature: row[headers.indexOf("Signature")],
        };
      });

      // 更新数据源
      data.value = transformedData;
      console.log(data);
    }
  };

  fileReader.readAsBinaryString(file);
};

// 文本截断函数
function truncateText(text, maxLength) {
  return text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
}

onMounted(() => {
  // 初始化时的其他操作
});
</script>
